﻿using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;

namespace Common.Infrastructure.Service
{
    public class UserTokenService : IUserTokenService
    {
        private readonly IHttpContextAccessor contextAccessor;
        private readonly UserToken userToken;

        public UserTokenService(IHttpContextAccessor accessor)
        {
            this.contextAccessor = accessor;

            try
            {
                var token = this.contextAccessor?.HttpContext?.Request?.Headers["Authorization"].ToString().Replace("Bearer ", string.Empty);
                if (!string.IsNullOrEmpty(token))
                {
                    JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                    var user = handler.ReadJwtToken(token);
                    var userData = user.Payload["UserData"] == null ? "{}" : user.Payload["UserData"].ToString();
                    userToken = !string.IsNullOrEmpty(userData) ? userData.ToObjectFromJson<UserToken>() : null;
                }
            }
            catch
            {
            }
        }

        public UserToken GetUserToken()
        {
            if (this.userToken != null)
            {
                return this.userToken;
            }

            var request = this.contextAccessor?.HttpContext?.Request;
            if (request != null)
            {
                var headers = request?.Headers;
                if (headers != null)
                {
                    var headToken = headers["UToken"];
                    if (headToken.Any() && !string.IsNullOrEmpty(headToken[0]))
                    {
                        return headToken[0].ToObjectFromJson<UserToken>();
                    }
                }
            }

            return this.userToken ?? new UserToken();
        }

        public string GetBearerAuth()
        {
            return this.contextAccessor?.HttpContext?.Request?.Headers["Authorization"].ToString().Replace("Bearer ", string.Empty);
        }
    }
}
